import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp

from models.Authentication import *
import Cookie
import uuid

class Login(webapp.RequestHandler):
  
  def get(self, flash=None):
    """Responds to http get request to /login. 
    Method simply renders the login template"""
    template_values = {"flash":flash}
    path= os.path.join(os.path.dirname(__file__), "../templates/login.html")
    self.response.out.write(template.render(path, template_values))
    
  def post(self):
    """Responds to HTTP POST to /login.
    Extract the values from the form post and calls the function that 
    verifies whether or not login info is valid."""

    attempted_email = self.request.get("user")
    attempted_password = self.request.get("password")
    
    # call the function that performs authentication check
    res = authenticate(email=attempted_email, password=attempted_password)
    
    # if there is a user returned from authenticate then set the necessary
    # cookie value
    if res:
      session = self.create_session(user=res)
      
      # add the new cookie values to the response header
      self.response.headers.add_header('Set-Cookie', session.output("header="))
      return self.redirect("/group")
    
    # if the login info was bad redirect them back to /login and display a 
    # flash.
    else:
      logging.info("I got here")
      flash = "Your Username or Password was incorrect please try again"
      self.get(flash=flash)
     
    
  def create_session(self, user=None):
    """This is a  implementation method that is used to create the  
    actual session object that we will return to the user"""
    cookie = Cookie.SimpleCookie()
    cookie["user_id"] = user.key().id()
    cookie["session_id"] = str(uuid.uuid4())
    
    return cookie
    
    
class Logout(webapp.RequestHandler):
  """Class is responsible for handling all request to /logout.
  will only respond to get http verbs. """

  def get(self):
    """Responds to http get /logout. Creates new cookie values that indicate
    that the user is not logged in and returns the user to the login page."""
    # create the new invalid cookie
    cookie = Cookie.SimpleCookie()
    cookie["user_id"] = 0
    cookie["session_id"] = -1
    # set the cookie in http header
    self.response.headers.add_header('Set-Cookie', cookie.output("header="))
    
    # redirect to login page
    return self.redirect("/login")